package com.lej.share.core

import android.app.Activity
import android.content.*
import android.widget.Toast
import com.lej.wx.PlatformUtil
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage


enum class ShareTarget {
    WEIXIN,
    QZONE,
    WEIXIN_CIRCLE,
    SINA,
    GENERIC,
    COPY_LINK,
    QQ;

    fun getMedia() = when (this) {
        WEIXIN -> SHARE_MEDIA.WEIXIN
        QQ -> SHARE_MEDIA.QQ
        SINA -> SHARE_MEDIA.SINA
        WEIXIN_CIRCLE -> SHARE_MEDIA.WEIXIN_CIRCLE
        QZONE -> SHARE_MEDIA.QZONE
        GENERIC -> SHARE_MEDIA.GENERIC
        else -> SHARE_MEDIA.GENERIC
    }

    fun checkShare(context: Context): Boolean = when (this) {
        WEIXIN -> PlatformUtil.isWeChatAvailable(context)
        QQ -> PlatformUtil.isQQClientAvailable(context)
        SINA -> PlatformUtil.isWeiboClientAvailable(context)
        WEIXIN_CIRCLE -> PlatformUtil.isWeChatAvailable(context)
        QZONE -> PlatformUtil.isQQClientAvailable(context)
        else -> true
    }

    fun share(activity: Activity, text: String, image: UMImage? = null) {
        if (!checkShare(activity)) {
            Toast.makeText(activity, "客户端似乎没有安装", Toast.LENGTH_SHORT).show()
            return
        }
        if (this == COPY_LINK) {
            //复制功能
            val cm = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            cm.setPrimaryClip(ClipData.newPlainText(null, text))
            return
        }
        if (this == QQ && image == null) {
            val intent = Intent("android.intent.action.SEND")
            intent.type = "text/plain"
            intent.putExtra(Intent.EXTRA_SUBJECT, "分享")
            intent.putExtra(Intent.EXTRA_TEXT, text)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            intent.component = ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity")
            activity.startActivity(intent)
            return
        }
        ShareAction(activity)
            .setPlatform(getMedia())//传入平台
            .withText(text)
            .withMedia(image)
            .setCallback(object : UMShareListener {
                override fun onResult(p0: SHARE_MEDIA?) {
                    print("onResult")
                }

                override fun onCancel(p0: SHARE_MEDIA?) {
                    print("onCancel")
                }

                override fun onError(p0: SHARE_MEDIA?, p1: Throwable?) {
                    print(p1?.message)
                }

                override fun onStart(p0: SHARE_MEDIA?) {
                    print("onStart")
                }
            })//回调监听器
            .share()
    }

}